﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EM.Repository.utility;
using System.Data;
using System.Data.SqlClient;
using Telerik.WebControls;
using System.Text;

namespace EM.reports.expense
{
    public partial class _default : System.Web.UI.Page
    {

        protected Conversion oC = new Conversion();
        protected DbHelper dsrv = new DbHelper();

        FillCombo fc = new FillCombo();

        private bool hasFULLAccess = false;
        private bool hasBMAccess = false;
        private bool hasLIMITEDAccess = false;


        protected void Page_Load(object sender, EventArgs e)
        {

            Authentication ua = new Authentication();
            ua.CheckRolePageAuthentication(19, Authentication.RedirectionURLTypes.LoginPage);

            hasFULLAccess = ua.HasPageFunctionAuthentication(19, "FULL");
            hasBMAccess = ua.HasPageFunctionAuthentication(19, "BM");
            hasLIMITEDAccess = ua.HasPageFunctionAuthentication(19, "LIMITED");

            if (!Page.IsPostBack)
            {
                DateTime defaultDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                rdpSTARTDATE.SelectedDate = defaultDate;
                rdpENDDATE.SelectedDate = defaultDate.AddMonths(1).AddDays(-1);

                fc.ExpenseType(ddlEXPENSETYPE, 0, true, Convert.ToInt32(Session["WORKGROUPID"]));
                fc.LookUpValue(ddlEXPENSEPAYMENTTYPE, "", true, "EXPENSE_PAYMENT_TYPE", Session["LANGCODE"].ToString());

                if (hasFULLAccess)
                {
                    fc.User(ddlUSER, "0", true, Convert.ToInt32(Session["WORKGROUPID"]));
                    ddlUSER.Enabled = true;
                }
                else
                {
                    if (hasBMAccess)
                    {
                        fc.User(ddlUSER, "0", true, Convert.ToInt32(Session["BRANCHID"]));
                        ddlUSER.Enabled = true;
                    }
                    else
                    {
                        ddlUSER.Enabled = false; 
                    }
                }
            }
        }

        private DataTable LoadData()
        {
            SqlCommand cmd = new SqlCommand();
            StringBuilder builder = new StringBuilder();
            builder.Append(@"SELECT B.* FROM 
                            (
                            SELECT A.*, C.CURRENCYCODE,
                            CASE WHEN A.EXPENSEPAYMENTTYPE = 'CC' THEN (SELECT CREDITCARDNAME FROM TBLCREDITCARD WHERE CREDITCARDID = A.ENTITYID)
                            WHEN A.EXPENSEPAYMENTTYPE = 'BT' THEN (SELECT BANKACCOUNTNAME FROM TBLBANKACCOUNT WHERE BANKACCOUNTID = A.ENTITYID)
                            ELSE 'Nakit' END AS ENTITYNAME  FROM
                            (
                                SELECT E.EXPENSEID, E.EXPENSETYPEID, ET.EXPENSETYPENAME, E.CURRENCYID, E.INSTALLMENTFLG,
                                E.ENTITYID,E.AMOUNT, E.INSTALLMENTCOUNT,E.INSTALLMENTSTARTDATE, E.EXPENSEPAYMENTTYPE, L.LOOKUPNAME AS EXPENSEPAYMENTTYPENAME,
                                EXPENSEDATE, E.EXPENSEUSERID, U.USERDESC AS EXPENSEUSER,E.DESCRIPTION  FROM TBLEXPENSE E, TBLEXPENSETYPE ET, TBLLOOKUPVALUE_L L, TBLUSER U
                                WHERE E.EXPENSETYPEID = ET.EXPENSETYPEID
                                AND E.EXPENSEPAYMENTTYPE = L.LOOKUPVALUE AND L.LOOKUPTYPE = 'EXPENSE_PAYMENT_TYPE' AND L.LANGCODE = 'TR'
                                AND E.EXPENSEUSERID = U.USERID AND E.WORKGROUPID = " + Session["WORKGROUPID"]);
            if (ddlEXPENSETYPE.SelectedValue != "" && ddlEXPENSETYPE.SelectedValue != "0")
            {
                builder.Append(" AND E.EXPENSETYPEID = @EXPENSETYPEID");
                cmd.Parameters.AddWithValue("@EXPENSETYPEID", ddlEXPENSETYPE.SelectedValue);
            }
            if (ddlEXPENSEPAYMENTTYPE.SelectedValue != "" && ddlEXPENSEPAYMENTTYPE.SelectedValue != "0")
            {
                builder.Append(" AND E.EXPENSEPAYMENTTYPE = @EXPENSEPAYMENTTYPE");
                cmd.Parameters.AddWithValue("@EXPENSEPAYMENTTYPE", ddlEXPENSEPAYMENTTYPE.SelectedValue);
            }
            if (ddlEntity.SelectedValue != "" && ddlEntity.SelectedValue != "0")
            {
                builder.Append(" AND E.ENTITYID = @ENTITYID ");
                cmd.Parameters.AddWithValue("@ENTITYID", ddlEntity.SelectedValue);
            }
            if (!hasFULLAccess)
            {
                if (hasBMAccess)
                {
                    builder.Append(" AND E.BRANCHID = @BRANCHID");
                    cmd.Parameters.AddWithValue("@BRANCHID", Session["BRANCHID"]);

                    if (ddlUSER.SelectedValue != "" && ddlUSER.SelectedValue != "0")
                    {
                        builder.Append(" AND E.EXPENSEUSERID = @EXPENSEUSERID");
                        cmd.Parameters.AddWithValue("@EXPENSEUSERID", ddlUSER.SelectedValue);
                    }
                }
                else
                {
                    builder.Append(" AND E.EXPENSEUSERID = @EXPENSEUSERID");
                    cmd.Parameters.AddWithValue("@EXPENSEUSERID", Session["USERID"]);
                }
            }
            else
            {
                if (ddlUSER.SelectedValue != "" && ddlUSER.SelectedValue != "0")
                {
                    builder.Append(" AND E.EXPENSEUSERID = @EXPENSEUSERID");
                    cmd.Parameters.AddWithValue("@EXPENSEUSERID", ddlUSER.SelectedValue);
                }
            }

            if (rdpSTARTDATE.SelectedDate != rdpSTARTDATE.MinDate)
            {
                builder.Append(" AND E.EXPENSEDATE >= @EXPENSEDATESTART");
                cmd.Parameters.AddWithValue("@EXPENSEDATESTART", rdpSTARTDATE.SelectedDate);
            }

            if (rdpENDDATE.SelectedDate != rdpENDDATE.MinDate)
            {
                builder.Append(" AND E.EXPENSEDATE <= @EXPENSEEND");
                cmd.Parameters.AddWithValue("@EXPENSEEND", rdpENDDATE.SelectedDate);
            }

            builder.Append(@") AS A 
                LEFT OUTER JOIN TBLCURRENCY C ON A.CURRENCYID = C.CURRENCYID WHERE 1 = 1
            AND (A.INSTALLMENTCOUNT IS NULL OR A.INSTALLMENTCOUNT = 0 AND A.EXPENSEPAYMENTTYPE <> 'CC')
            AND A.INSTALLMENTFLG = 'N'");

            if (chkInstallment.Checked)
            {
                builder.Append(@"
                UNION ALL
                SELECT E.EXPENSEID, E.EXPENSETYPEID, ET.EXPENSETYPENAME,C.CURRENCYID,'Y',
                E.ENTITYID,I.AMOUNT, E.INSTALLMENTCOUNT,E.INSTALLMENTSTARTDATE,'CC', 'Kredi Kartı',
                I.INSTALMENTDATE, E.EXPENSEUSERID, U.USERDESC AS EXPENSEUSER,  ET.EXPENSETYPENAME + '(' +  I.INSTALLMENTORDER + '. Taksit)' , C.CURRENCYCODE,
                CC.CREDITCARDNAME FROM TBLEXPENSE E, TBLEXPENSETYPE ET, TBLUSER U, TBLINSTALLMENT I, TBLCREDITCARD CC, TBLCURRENCY C
                WHERE E.EXPENSETYPEID = ET.EXPENSETYPEID
                AND E.EXPENSEUSERID = U.USERID
                AND E.EXPENSEID = I.EXPENSEID
                AND CC.CREDITCARDID = I.CREDITCARDID
                AND C.CURRENCYID = E.CURRENCYID AND I.WORKGROUPID = " + Session["WORKGROUPID"]);

                if (ddlEXPENSETYPE.SelectedValue != "" && ddlEXPENSETYPE.SelectedValue != "0")
                {
                    builder.Append(" AND E.EXPENSETYPEID = @EXPENSETYPEID");
                }
                if (ddlEXPENSEPAYMENTTYPE.SelectedValue != "" && ddlEXPENSEPAYMENTTYPE.SelectedValue != "0")
                {
                    builder.Append(" AND E.EXPENSEPAYMENTTYPE = @EXPENSEPAYMENTTYPE");
                }
                if (ddlEntity.SelectedValue != "" && ddlEntity.SelectedValue != "0")
                {
                    builder.Append(" AND E.ENTITYID = @ENTITYID ");
                }
                if (!(bool)HttpContext.Current.Session["UserIsAnAdmin"])
                {
                    builder.Append(" AND E.EXPENSEUSERID = @EXPENSEUSERID");
                }
                else
                {
                    if (ddlUSER.SelectedValue != "" && ddlUSER.SelectedValue != "0")
                    {
                        builder.Append(" AND E.EXPENSEUSERID = @EXPENSEUSERID");
                    }
                }

                if (rdpSTARTDATE.SelectedDate != rdpSTARTDATE.MinDate)
                {
                    builder.Append(" AND I.INSTALMENTDATE >= @EXPENSEDATESTART");
                }

                if (rdpENDDATE.SelectedDate != rdpENDDATE.MinDate)
                {
                    builder.Append(" AND I.INSTALMENTDATE <= @EXPENSEEND");
                }
            }
            builder.Append(" ) AS B ORDER BY EXPENSEDATE ASC ");

            cmd.CommandText = builder.ToString();


            DataTable dt = this.dsrv.GetDataTable(cmd, "EXPENSE");
            return dt;
        }

        private void BindGrid()
        {
            DataTable dt = new DataTable();
            dt = LoadData();
            rgMaster.DataSource = dt;

            rgMaster.MasterTableView.NoMasterRecordsText = "Kayıt bulunamadı.";
            rgMaster.StatusBarSettings.ReadyText = dt.Rows.Count + " adet kayıt bulundu.";

            rgMaster.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }


        double totalAmount = 0;
        double totalAmountTotal = 0;

        Dictionary<string, double> _totalAmount = new Dictionary<string, double>();
        Dictionary<string, double> _totalAmountTotal = new Dictionary<string, double>();


        protected void rgMaster_ItemDataBound(object sender, GridItemEventArgs e)
        {
            Conversion oC = new Conversion();
            DataRowView drw = (DataRowView)e.Item.DataItem;
            if (e.Item.ItemType == GridItemType.Header)
            {
                this._totalAmount.Clear();
            }
            else if (e.Item.ItemType == GridItemType.AlternatingItem || e.Item.ItemType == GridItemType.Item)
            {
                DataRowView row = e.Item.DataItem as DataRowView;

                double amount = 0;
                if (row["AMOUNT"].ToString() != "")
                    amount = Convert.ToDouble(row["AMOUNT"]);
                string currencyCode = row["CURRENCYCODE"].ToString();

                e.Item.Cells[rgMaster.Columns.FindByUniqueName("AMOUNT").OrderIndex].Text = oC.CNumS2C(amount) + " " + currencyCode;

                totalAmount += amount;

                if (_totalAmount.ContainsKey(currencyCode))
                    _totalAmount[currencyCode] = _totalAmount[currencyCode] + Convert.ToDouble(drw["AMOUNT"]);
                else
                    _totalAmount.Add(currencyCode, Convert.ToDouble(drw["AMOUNT"]));

            }
            else if (e.Item.ItemType == GridItemType.Footer)
            {

                DataTable dt = rgMaster.DataSource as DataTable;
                this._totalAmountTotal.Clear();

                totalAmountTotal = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    totalAmountTotal += Convert.ToDouble(dt.Rows[i]["AMOUNT"]);

                    if (_totalAmountTotal.ContainsKey(row["CURRENCYCODE"].ToString()))
                        _totalAmountTotal[row["CURRENCYCODE"].ToString()] = _totalAmountTotal[row["CURRENCYCODE"].ToString()] + Convert.ToDouble(row["AMOUNT"]);
                    else
                        _totalAmountTotal.Add(row["CURRENCYCODE"].ToString(), Convert.ToDouble(row["AMOUNT"]));
                }

                e.Item.Cells[rgMaster.Columns.FindByUniqueName("EXPENSEDATE").OrderIndex].Text = "Sayfa Toplamı :<br />Genel Toplam :";
                e.Item.Cells[rgMaster.Columns.FindByUniqueName("AMOUNT").OrderIndex].Style.Add("text-align", "right");


                string _kickbackString = "#SAYFA#<br />#GENEL#";
                string _kickbackStringSayfa = "";
                string _kickbackStringGenel = "";

                foreach (var item in _totalAmount)
                {
                    if (item.Value > 0)
                        _kickbackStringSayfa += string.Format("{0}&nbsp;{1}<br />", oC.CNumS2C(item.Value), item.Key);
                }
                foreach (var item in _totalAmountTotal)
                {
                    if (item.Value > 0)
                        _kickbackStringGenel += string.Format("{0}&nbsp;{1}<br />", oC.CNumS2C(item.Value), item.Key);
                }

                _kickbackString = _kickbackString.Replace("#SAYFA#", _kickbackStringSayfa);
                _kickbackString = _kickbackString.Replace("#GENEL#", _kickbackStringGenel);

                e.Item.Cells[rgMaster.Columns.FindByUniqueName("AMOUNT").OrderIndex].Text = _kickbackString;

                totalAmount = 0;
                totalAmountTotal = 0;
            }
            else if (e.Item.ItemType == Telerik.WebControls.GridItemType.Pager)
            {
                Label lblRecordCount = new Label();
                e.Item.Controls[0].Controls.AddAt(0, lblRecordCount);
                lblRecordCount.Text = rgMaster.StatusBarSettings.ReadyText + " | sayfaya git : ";

                rgMaster.ShowStatusBar = rgMaster.PageCount <= 1 ? true : false;
            }
        }

        protected void rgMaster_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)
        {
            if (IsPostBack)
            {
                DataTable dt = new DataTable();
                dt = LoadData();
                rgMaster.DataSource = dt;

                rgMaster.MasterTableView.NoMasterRecordsText = "Kayıt bulunamadı.";
                rgMaster.StatusBarSettings.ReadyText = dt.Rows.Count + " adet kayıt bulundu.";
            }
        }

        protected void rgMaster_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Page" || e.CommandName == "Sort")
            {
                BindGrid();
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                rgMaster.ExportSettings.FileName = "Expense";
                rgMaster.ExportSettings.ExportOnlyData = true;
                rgMaster.ExportSettings.IgnorePaging = true;
                rgMaster.ExportSettings.OpenInNewWindow = true;
                rgMaster.MasterTableView.ExportToExcel();
            }
            catch
            {
                ;
            }
        }

        protected void ddlEXPENSEPAYMENTTYPE_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlEXPENSEPAYMENTTYPE.SelectedValue == "CC")
            {
                fc.CreditCard(ddlEntity, 0, true, 0,  Convert.ToInt32(Session["WORKGROUPID"]));
            }
            else if (ddlEXPENSEPAYMENTTYPE.SelectedValue == "BT")
            {
                fc.BankAccount(ddlEntity, 0, true, 0, Convert.ToInt32(Session["WORKGROUPID"]));
            }
        }
    }
}